package com.github.niefy.modules.wx.handler;

import com.github.niefy.modules.wx.service.MsgReplyService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.builder.outxml.TextBuilder;
import me.chanjar.weixin.mp.util.WxMpConfigStorageHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Binary Wang
 */
@Component
public class ScanHandler extends AbstractHandler {
    @Autowired
    MsgReplyService msgReplyService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map,
                                    WxMpService wxMpService, WxSessionManager wxSessionManager) {
        //扫码事件处理
        this.logger.info("用户扫描带参二维码 OPENID: " + wxMpXmlMessage.getFromUser() + "携带场景值 SCENESTR:" + wxMpXmlMessage.getEventKey());
        String appid = WxMpConfigStorageHolder.get();
        //msgReplyService.tryAutoReply(appid, true, wxMpXmlMessage.getFromUser(), wxMpXmlMessage.getEventKey());
        //msgReplyService.tryAutoReply(appid, false, wxMpXmlMessage.getFromUser(), wxMpXmlMessage.getEventKey());
        //组装回复消息
        WxMpXmlOutMessage rs = getWxMpXmlOutMessage(wxMpXmlMessage, wxMpXmlMessage.getEventKey());
        return rs;
    }

    /**
     * TODO demo,扫码回复渠道参数消息,后续有扫码的需求改这里
     * 组装回复消息，并记录消息
     * @return
     */
    public static WxMpXmlOutMessage getWxMpXmlOutMessage(WxMpXmlMessage wxMpXmlMessage, String eventKey){
        WxMpXmlOutMessage wxMpXmlOutMessage =  new TextBuilder().fromUser(wxMpXmlMessage.getToUser()).toUser(wxMpXmlMessage.getFromUser()).content(eventKey.substring(0, eventKey.indexOf(':')) + "用户绑定成功").build();;
        return wxMpXmlOutMessage;
    }
}
